<?php
include("session.php");
include("config.php");

if (!validate(LEVEL_BILL, "bill_time.php", $db, "maintime.php"))
    exit();

$isSearchpost =  isset($_POST['start']) && $_SERVER['REQUEST_METHOD'] === 'POST';
$isBillpost = isset($_POST['startbill']) && $_SERVER['REQUEST_METHOD'] === 'POST';
$timebilled = false;
if ($isBillpost) {
    $sql = "UPDATE time t INNER JOIN task ta ON t.task_id = ta.id
     set t.billdate = NOW()
     WHERE t.billdate is null and t.start >= ? and t.stop <= ? and ta.project_id = ?";
    $result = get_db_result($db, $sql, "ssi", $_POST['startbill'], $_POST['stopbill'], $_POST['projectbill']);
    if (!$result) {
        printf (RLang("err_db_function_failed"), 'get_db_result',   $db->errno, $db->error);
        die($sql);
    }
    if ($db->affected_rows == 0) {
        printf (RLang("err_db_function_has_no_effect"),  RLang("bill_time"));
        print_r($_POST);
        die();
    } else
        $timebilled = true;
}

$sums = [];
?>
<html>

<head>
    <title>Easy Time Tracker</title>
    <script src="/datepicker/easy.datepicker.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="/datepicker/vanilla.datepicker.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/timetracker.css" type="text/css" media="screen" />
</head>

<body style="height:100%">
    <a href='maintime.php' class='tooltip'><img src='icons/22/edit-undo.png'>
        <div class='rtooltiptext'><?php ELang("back"); ?></div>
    </a>
    <div alignment="horizontal" style="display:flex; flex-direction: row; justify-content: left; align-items: center; width:100%; height:90%;">
        <!-- Time Table -->
        <div style="height:100%; width:100%;">
            <table cellspacing="0" cellpadding="0" border="0" width="100%">
                <tr>
                    <td>
                        <table id="main_table" class="DataTable">
                            <col width="180">
                            <col width="180">
                            <col width="150">
                            <col width="150">
                            <col width="auto">
                            <col width="50">
                            <tr>
                                <th><?php ELang("start"); ?></th>
                                <th><?php ELang("stop"); ?></th>
                                <th><?php ELang("project"); ?></th>
                                <th><?php ELang("task"); ?></th>
                                <th><?php ELang("text"); ?></th>
                                <th><?php ELang("hrs"); ?></th>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td>
                        <!-- Time summary -->
                        <div id="mainscroll" class="Scrollable" style="height:<?php if ($_SESSION['sheight'] == 0) echo ("300");
                                                                                else echo ($_SESSION['sheight'] / 100 * 73); ?>px">
                            <table id="main_table" class="DataTable">
                                <col width="180">
                                <col width="180">
                                <col width="150">
                                <col width="150">
                                <col width="auto">
                                <col width="50">
                                <?php
                                if ($isSearchpost) {

                                    $sql = "SELECT t.id AS id, t.start AS start, t.stop AS stop, p.name AS project, ta.name AS task, t.text AS text FROM time t 
                            INNER JOIN task ta ON t.task_id = ta.id INNER JOIN project p ON ta.project_id = p.id WHERE t.billdate is null and 
                            t.start >= ? and t.stop <= ? and ta.project_id = ? order by t.id";
                                    $startdatetime = $_POST['start'] . " 00:00:00";
                                    $stopdatetime = $_POST['end'] . " 23:59:59";
                                    $result = get_db_result($db, $sql, "ssi", $startdatetime, $stopdatetime, $_POST['project']);
                                    if (!$result) {
                                        printf (RLang("err_db_function_failed"), 'get_db_result',   $db->errno, $db->error);
                                        die($sql);
                                    }
                                    $rowcnt = mysqli_num_rows($result);
                                    for ($i = 0; $i < $rowcnt; $i++) {
                                        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                                        $hrs = get_hour_diff_from_sql_datetime($row['start'], $row['stop']);
                                        if (!$hrs) {
                                            //In bill_time this should never happen since we already check this at record time, but you never know if some1 does evil vodoo with the DB
                                            $_SESSION['msgtype'] = "error";
                                            $_SESSION['msg'] = RLang("err_start_after_stop") .  sprintf(". ".RLang("err_invalid_db_entry"), 'time',  $row['id']) ;
                                            header("Location: maintime.php");
                                            exit();
                                        }
                                        printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $row['start'], $row['stop'], $row['project'], $row['task'], $row['text'], $hrs);
                                        if (!isset($sums[$row['task']]))
                                            $sums[$row['task']]  = $hrs;
                                        else
                                            $sums[$row['task']]  += $hrs;
                                    }
                                    mysqli_free_result($result);
                                }
                                ?>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <!-- Settings Bar -->
        <div class="BorderBox" style="width:300px;height:100%">
            <form action="" method="post">
                <table class="navbar">
                    <col width="180">
                    <col width="180">
                    <tr>
                        <td><?php ELang("begin"); ?></td>
                        <td><input type="text" name="start" class="datepicker" <?php if ($isSearchpost) printf("value=%s", $_POST['start']); ?>></td>
                    </tr>
                    <tr>
                        <td><?php ELang("end"); ?></td>
                        <td><input type="text" name="end" class="datepicker" <?php if ($isSearchpost) printf("value=%s", $_POST['end']); ?>></td>
                    </tr>
                    <tr>
                        <td colspan="2"> <?php printf("%S(%s)",RLang("project"), RLang("hrs")); ?></td>

                    </tr>
                    <tr>
                        <td colspan="2">
                            <select name="project">
                                <?php
                                $sql = "SELECT p.name AS name, p.id AS id, sum(TIMESTAMPDIFF(HOUR,ti.start, ti.stop)) as hrs FROM project p INNER JOIN task t ON p.id = t.project_id LEFT JOIN time ti ON t.id = ti.task_id where ti.id is not null and ti.billdate is null GROUP BY p.name, p.id";
                                if (!$result = get_db_result($db, $sql, null)) {
                                    echo ($sql . " ");
                                    die(mysqli_error($db));
                                }

                                $rowcnt = mysqli_num_rows($result);
                                $canbilltime = $rowcnt > 0;
                                for ($e = 0; $e < $rowcnt; $e++) {
                                    $orow = mysqli_fetch_array($result, MYSQLI_ASSOC);
                                    $oid = $orow['id'];
                                    echo ("<option value='$oid' ");
                                    if ($isSearchpost && $oid == $_POST['project'])
                                        echo ("selected");
                                    printf(">%s(%u)</option>\r\n", $orow['name'], $orow['hrs']);
                                }
                                mysqli_free_result($result);
                                ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="<?php ELang("search") ?>"></td>
                    </tr>
                </table>
            </form>
            <div id="sums" style="height:20%;">
                <table cellspacing="0" cellpadding="0" border="0" width="100%">
                    <tr>
                        <td>
                            <table class="DataTable">
                                <col width="50px">
                                <col width="100px">
                                <tr>
                                    <th><?php ELang("task"); ?></th>
                                    <th><?php printf("%s %s", RLang("sum"), RLang("hours")); ?></th>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="Scrollable" style="height:100px">
                                <table class="DataTable">
                                    <?php
                                    foreach ($sums as $t => $s)
                                        printf("<tr><td>%s</td><td>%s</td></tr>", $t, $s);
                                    ?>
                                </table>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <?php
            if ($isSearchpost && $canbilltime) {
                echo ("<form action='' method='post'>\r\n");
                printf("<input type='hidden' name='startbill' value='%s'>\r\n", $startdatetime);
                printf("<input type='hidden' name='stopbill' value='%s'>\r\n", $stopdatetime);
                printf("<input type='hidden' name='projectbill' value='%s'>\r\n", $_POST['project']);
                printf ("<input type='submit' value='%s'>", RLang("bill_selected_time"));
                echo ("</form>\r\n");
            } else if ($timebilled) {
                printf("<div class=\"msg\" >%s</div>", sprintf("msg_time_billed", $_POST['startbill'], $_POST['stopbill'], $_POST['projectbill']));
            }
            ?>
        </div>


    </div>

</body>
<script type="text/javascript">
    datepicker.create('.datepicker', {
        firstDayOfWeek: 1,
        months: {
            short: [<?php ELang("datepicker_months_short"); ?>],
            long: [<?php ELang("datepicker_months_long"); ?>]
        },
        weekdays: {
            short: [<?php ELang("datepicker_weekdays_short"); ?>],
            long: [<?php ELang("datepicker_weekdays_long"); ?>]
        },
        outputFormat: '%Y-%m-%d'
    });
</script>

</html>